<template>
  <view class="history-page">
    <view class="history-topbar">
      <text class="history-title">历史记录</text>
      <button class="danger top-clear" @click="confirmClear">清空</button>
    </view>
    
      <view v-if="records.length === 0" class="empty">
        <text class="empty-text">暂无历史记录</text>
      </view>
      <view v-else>
        <view v-for="rec in records" :key="rec.timestamp">
          <view class="record-card" @click="toggleExpand(rec)" @longpress="enterSelectMode(rec)">
            <view class="card-header">
              <text class="time">{{ formatTime(rec.timestamp) }}</text>
              <view class="tags">
                <text class="tag" v-if="rec.input.considerInflation">通货膨胀</text>
                <text class="tag" v-if="rec.input.useMonteCarlo">蒙特卡洛模拟</text>
              </view>
            </view>
            <view class="row">
              <text class="label">退休时积累金额</text>
              <text class="value">¥{{ formatCurrency(rec.output.nestEgg) }}</text>
            </view>
            <view class="row">
              <text class="label">退休后每年可取出金额</text>
              <text class="value">¥{{ formatCurrency(rec.output.withdrawal) }}</text>
            </view>
            <view class="row" v-if="rec.output.mcMedian">
              <text class="label">模拟中位数</text>
              <text class="value">¥{{ formatCurrency(rec.output.mcMedian) }}</text>
            </view>

            <view class="check-btn" v-if="selectMode" :class="{ selected: isSelected(rec) }" @click.stop="toggleSelect(rec)">
              <text v-if="isSelected(rec)">✔</text>
              <text v-else>○</text>
            </view>
          </view>
          <uni-transition :show="expandedKey === rec.timestamp" mode-class="slide-bottom" :duration="180">
            <view class="sub-card">
              <view class="row">
                <text class="label">详细参数</text>
              </view>
              <view class="row small">
                <text class="hint">当前年龄 {{ rec.input.currentAge }}岁，退休年龄 {{ rec.input.retireAge }}岁</text>
              </view>
              <view class="row small">
                <text class="hint">当前储蓄 ¥{{ formatCurrency(rec.input.currentSavings) }}</text>
              </view>
              <view class="row small">
                <text class="hint">每年新增储蓄 ¥{{ formatCurrency(rec.input.annualContribution) }}</text>
              </view>
              <view class="row small">
                <text class="hint">投资年收益率 {{ rec.input.returnRate }}%</text>
              </view>
              <view class="row small">
                <text class="hint">退休后预期寿命 {{ rec.input.lifespan }}岁</text>
              </view>
              <view class="row small" v-if="rec.input.considerInflation">
                <text class="hint">通货膨胀率 {{ rec.input.inflationRate }}%</text>
              </view>
              <view class="row small" v-if="rec.input.useMonteCarlo">
                <text class="hint">投资收益率标准差 {{ rec.input.returnStd }}%，模拟次数 {{ rec.input.simTimes }}</text>
              </view>
            </view>
          </uni-transition>
          <uni-transition :show="selectMode && manageKey === rec.timestamp" mode-class="slide-bottom" :duration="180">
            <view class="manage-bar">
              <button class="manage-btn" @click="selectAll">全选</button>
              <button class="manage-btn danger" @click="deleteSelected">删除</button>
            </view>
          </uni-transition>
        </view>
      </view>
  </view>
</template>

<script>
export default {
  data() {
    return { records: [], expandedKey: null, selectMode: false, selectedKeys: [], manageKey: null }
  },
  onShow() {
    this.loadRecords()
  },
  methods: {
    loadRecords() {
      try {
        const list = uni.getStorageSync('calcHistory') || []
        this.records = Array.isArray(list) ? list : []
      } catch (e) {
        this.records = []
      }
    },
    formatCurrency(n) {
      const v = Number(n || 0)
      const fixed = v.toFixed(2)
      const parts = fixed.split('.')
      const integerPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      return integerPart + '.' + parts[1]
    },
    formatTime(ts) {
      const d = new Date(ts)
      const pad = n => String(n).padStart(2, '0')
      const y = d.getFullYear()
      const m = pad(d.getMonth() + 1)
      const day = pad(d.getDate())
      const hh = pad(d.getHours())
      const mm = pad(d.getMinutes())
      return `${y}-${m}-${day} ${hh}:${mm}`
    },
    toggleExpand(rec) {
      if (this.selectMode) return
      this.expandedKey = this.expandedKey === rec.timestamp ? null : rec.timestamp
    },
    enterSelectMode(rec) {
      this.selectMode = true
      this.manageKey = rec.timestamp
      this.toggleSelect(rec)
    },
    toggleSelect(rec) {
      const k = rec.timestamp
      const idx = this.selectedKeys.indexOf(k)
      if (idx >= 0) {
        this.selectedKeys.splice(idx, 1)
      } else {
        this.selectedKeys.push(k)
      }
    },
    isSelected(rec) {
      return this.selectedKeys.includes(rec.timestamp)
    },
    selectAll() {
      this.selectedKeys = this.records.map(r => r.timestamp)
    },
    deleteSelected() {
      if (!this.selectedKeys.length) {
        uni.showToast({ title: '未选择记录', icon: 'none' })
        return
      }
      const toDelete = new Set(this.selectedKeys)
      // 更新内存列表
      this.records = this.records.filter(r => !toDelete.has(r.timestamp))
      // 更新本地存储
      try {
        let storage = uni.getStorageSync('calcHistory') || []
        if (Array.isArray(storage)) {
          storage = storage.filter(r => !toDelete.has(r.timestamp))
          uni.setStorageSync('calcHistory', storage)
        } else {
          uni.setStorageSync('calcHistory', [])
        }
      } catch (e) {}
      this.selectedKeys = []
      this.selectMode = false
      this.manageKey = null
      uni.showToast({ title: '已删除', icon: 'none' })
    },
    confirmClear() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有历史记录吗？',
        success: (res) => {
          if (res.confirm) {
            try { uni.removeStorageSync('calcHistory') } catch (e) {}
            this.records = []
            uni.showToast({ title: '已清空', icon: 'none' })
          }
        }
      })
    }
  }
}
</script>

<style>
.history-page { background: #F9FAFB; min-height: 100vh; padding-bottom: 40rpx; }
.card { background: #FFFFFF; margin: 24rpx 30rpx; padding: 28rpx; border-radius: 24rpx; border: 2rpx solid #E5E7EB; box-shadow: 0 0 0 4rpx #fff, 0 8rpx 0 #cbd5e1, 0 18rpx 32rpx rgba(0,0,0,0.08); }
.section-title { font-size: 32rpx; font-weight: 700; color: #111827; margin-bottom: 16rpx; }
.item { padding: 18rpx 0; border-bottom: 2rpx dashed #E5E7EB; }
.item:last-child { border-bottom: 0; }
.record-card {
  width: 85%;
  margin: 16rpx auto;
  padding: 20rpx;
  border-radius: 20rpx;
  background: linear-gradient(#FFFFFF,#FFFFFF) padding-box, linear-gradient(180deg,#FF965B 0%, #FF6A39 100%) border-box;
  border: 2rpx solid transparent;
  box-shadow: 0 6rpx 0 #ffffff, 0 14rpx 22rpx rgba(0,0,0,0.08);
  position: relative; }
  .check-btn {
    position: absolute; right: -10rpx; top: 50%; transform: translateY(-50%);
    width: 56rpx; height: 56rpx; border-radius: 50%;
    background: #FFFFFF; border: 2rpx solid #E5E7EB;
    display: flex; align-items: center; justify-content: center;
    box-shadow: 0 4rpx 0 #ffffff, 0 10rpx 18rpx rgba(0,0,0,0.06);
    color: #111827; font-size: 28rpx;
  }
  .check-btn.selected { border-color: #10B981; color: #10B981; }
  .manage-bar {
    width: 85%; margin: 8rpx auto 16rpx; padding: 14rpx;
    border-radius: 16rpx; background: #FFFFFF; border: 2rpx solid #E5E7EB;
    box-shadow: 0 4rpx 0 #ffffff, 0 10rpx 18rpx rgba(0,0,0,0.06);
    display: flex; justify-content: space-between;
  }
  .manage-btn {
    flex: 1; height: 72rpx; margin: 0 8rpx; border-radius: 16rpx;
    background: linear-gradient(#FFFFFF,#FFFFFF) padding-box, linear-gradient(180deg,#FF965B 0%, #FF6A39 100%) border-box;
    border: 2rpx solid transparent; color: #FF6A39; font-weight: 700; font-size: 30rpx;
    display: flex; align-items: center; justify-content: center;
    box-shadow: 0 6rpx 0 #E05E2A, 0 14rpx 22rpx rgba(0,0,0,0.12);
  }
  .manage-btn:active { transform: translateY(4rpx); box-shadow: 0 2rpx 0 #E05E2A; }

.card-header { display:flex; justify-content: space-between; align-items: center; margin-bottom: 6rpx; }
.tags { display:flex; gap: 8rpx; }
.time { color: #374151; font-size: 26rpx; font-weight: 600; }
.tag { padding: 6rpx 12rpx; border-radius: 12rpx; background: #FFF7ED; color: #D97706; font-size: 24rpx; border: 2rpx solid #F59E0B; }
.row { display: flex; align-items: center; justify-content: space-between; padding: 8rpx 0; }
.row.small { justify-content: flex-start; }
.label { color: #1F2937; font-size: 28rpx; }
.value { color: #111827; font-size: 28rpx; font-weight: 700; }
.hint { color: #6B7280; font-size: 24rpx; }
.empty { padding: 30rpx 0; text-align: center; }
.empty-text { color: #6B7280; font-size: 28rpx; }

.danger {
  width: auto; height: 80rpx; border-radius: 18rpx;
  background: #FFFFFF;
  color: #DC2626; font-weight: 700; font-size: 32rpx;
  display: flex; align-items: center; justify-content: center;
  border: 2rpx solid #FCA5A5;
  box-shadow: 0 6rpx 0 #ffffff, 0 14rpx 22rpx rgba(0,0,0,0.12);
}
.danger:active { transform: translateY(4rpx); box-shadow: 0 2rpx 0 #E5E7EB; }
.sub-card {
  width: 85%;
  margin: 8rpx auto 16rpx;
  padding: 18rpx;
  border-radius: 16rpx;
  background: #FFFFFF;
  border: 2rpx solid #E5E7EB;
  box-shadow: 0 4rpx 0 #ffffff, 0 10rpx 18rpx rgba(0,0,0,0.06);
}
 .history-topbar { display: flex; align-items: center; justify-content: space-between; padding: 20rpx 30rpx 0; }
 .history-title { font-size: 36rpx; font-weight: 800; color: #111827; }
 .top-clear { margin: 0; height: 64rpx; padding: 0 24rpx; border-radius: 16rpx; font-size: 28rpx; }
</style>